from comment.comviews import *
from utils.dbutils import DB_Config, MysqlTools
from utils.tokens import *
from .sqlmap import *
from django.http import HttpResponse
import json
from user_agents import parse

mysql_tools = MysqlTools(db_config=DB_Config.get("default"))


@format_response
def index(request):
    active = request.GET.get("active")
    body = json.loads(request.body.decode())
    time = body.get("time")
    params = body.get("params")
    appInfo = body.get("appInfo")
    if not all([time, params, appInfo]):
        return err_response(311)
    if active == "quit":  # 退出
        uid = body.get("uid")
        cache.delete(uid)
        return success_response()
    elif active == "login":
        sql = LoginSqlMap.LOGIN.format(**params)
        result = mysql_tools.select_one(sql)
        if not result:
            return err_response(311, "用户名或密码错误")
        # login success
        username = params.get("name")
        password = params.get("password")
        if not all([username, password]):
            return err_response(311)
        token = create_token(params["name"], params["password"])
        real_ip = get_ip(request)
        dict = {}
        dict["token"] = token
        dict["user_id"] = result["user_id"]
        return success_response(dict)
